<template>
  <div class="container">
    <Breadcrumb :items="['站点管理', '充电桩管理', '服务器关联']" />
    <a-card class="general-card" :title="deviceName ? `${deviceName} - 服务器关联` : '服务器关联'">
      <template #extra>
        <a-button type="primary" @click="goBack">
          <template #icon>
            <icon-arrow-left />
          </template>
          返回充电桩列表
        </a-button>
      </template>

      <!-- 操作栏 -->
      <div class="operation-bar">
        <div class="operation-left">
          <a-button type="primary" @click="openAddDialog">
            <template #icon>
              <icon-plus />
            </template>
            新增服务器关联
          </a-button>
        </div>
        <div class="operation-right">
          <a-button @click="refreshData">
            <template #icon>
              <icon-refresh />
            </template>
            刷新
          </a-button>
        </div>
      </div>

      <!-- 服务器关联列表 -->
      <a-table
        :loading="loading"
        :data="relationList"
        :pagination="pagination"
        @page-change="onPageChange"
        @page-size-change="onPageSizeChange"
        stripe
      >
        <template #columns>
          <a-table-column title="序号" :width="80">
            <template #cell="{ rowIndex }">
              {{ (pagination.current - 1) * pagination.pageSize + rowIndex + 1 }}
            </template>
          </a-table-column>
          <a-table-column title="充电桩编码" :width="150">
            <template #cell="{ record }">
              {{ record.pile.pileCode }}
            </template>
          </a-table-column>
          <a-table-column title="充电桩名称" :width="150">
            <template #cell="{ record }">
              {{ record.pile.pileName }}
            </template>
          </a-table-column>
          <a-table-column title="转发设备编号" :width="150">
            <template #cell="{ record }">
              {{ record.relation.forwardPileCode }}
            </template>
          </a-table-column>
          <a-table-column title="转发服务器" :width="200">
            <template #cell="{ record }">
              {{ `${record.server.serverName} (${record.server.serverIp}:${record.server.serverPort})` }}
            </template>
          </a-table-column>
          <a-table-column title="是否主服务器" :width="120">
            <template #cell="{ record }">
              <a-tag :color="record.relation.isPrimary === 1 ? 'green' : 'gray'">
                {{ record.relation.isPrimary === 1 ? '是' : '否' }}
              </a-tag>
            </template>
          </a-table-column>
          <a-table-column title="连接状态" :width="120">
            <template #cell="{ record }">
              <a-tag :color="getConnectionStatusColor(record.relation.connectionStatus)">
                {{ getConnectionStatusText(record.relation.connectionStatus) }}
              </a-tag>
            </template>
          </a-table-column>
          <a-table-column title="创建时间" :width="180">
            <template #cell="{ record }">
              {{ formatTime(record.relation.createTime) }}
            </template>
          </a-table-column>
          <a-table-column title="更新时间" :width="180">
            <template #cell="{ record }">
              {{ formatTime(record.relation.updateTime) }}
            </template>
          </a-table-column>
          <a-table-column title="操作" :width="200" fixed="right">
            <template #cell="{ record }">
              <a-space>
                <a-button type="text" size="small" @click="viewRelationDetail(record)">
                  详情
                </a-button>
                <a-button type="text" size="small" @click="openEditDialog(record)">
                  编辑
                </a-button>
                <a-button type="text" status="danger" size="small" @click="handleDelete(record)">
                  删除
                </a-button>
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-card>

    <!-- 新增/编辑服务器关联对话框 -->
    <a-modal
      v-model:visible="visible"
      :title="isEdit ? '编辑服务器关联' : '新增服务器关联'"
      width="600px"
      :footer="false"
      class="relation-modal"
    >
      <a-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-align="left"
        :label-col-props="{ span: 6 }"
        :wrapper-col-props="{ span: 18 }"
        class="relation-form"
      >
        <a-form-item label="充电桩编号">
          <a-input :model-value="pileCode" disabled />
        </a-form-item>
        <a-form-item field="forwardPileCode" label="转发设备编号" required>
          <a-input v-model="form.forwardPileCode" placeholder="请输入转发设备编号" />
        </a-form-item>
        <a-form-item field="serverId" label="转发服务器" required>
          <a-select v-model="form.serverId" placeholder="请选择转发服务器">
            <a-option v-for="server in serverList" :key="server.id" :value="server.id">
              {{ server.serverName }} ({{ server.serverIp }}:{{ server.serverPort }})
            </a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="isPrimary" label="是否主服务器">
          <a-radio-group v-model="form.isPrimary" type="button">
            <a-radio :value="1">是</a-radio>
            <a-radio :value="0">否</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item field="connectionStatus" label="连接状态">
          <a-radio-group v-model="form.connectionStatus" type="button">
            <a-radio :value="0">未连接</a-radio>
            <a-radio :value="1">已连接</a-radio>
            <a-radio :value="2">连接异常</a-radio>
          </a-radio-group>
        </a-form-item>

        <div class="form-footer">
          <a-space>
            <a-button @click="visible = false">取消</a-button>
            <a-button type="primary" @click="handleSubmit">提交</a-button>
          </a-space>
        </div>
      </a-form>
    </a-modal>

    <!-- 服务器关联详情对话框 -->
    <a-modal
      v-model:visible="detailVisible"
      title="服务器关联详情"
      @cancel="detailVisible = false"
      :footer="false"
      width="700px"
    >
      <div v-if="currentRelation" class="relation-detail">
        <a-descriptions :column="2" bordered size="large">
          <a-descriptions-item label="充电桩编码">{{ currentRelation.pile.pileCode }}</a-descriptions-item>
          <a-descriptions-item label="充电桩名称">{{ currentRelation.pile.pileName }}</a-descriptions-item>
          <a-descriptions-item label="转发设备编号">{{ currentRelation.relation.forwardPileCode }}</a-descriptions-item>
          <a-descriptions-item label="转发服务器">
            {{ `${currentRelation.server.serverName} (${currentRelation.server.serverIp}:${currentRelation.server.serverPort})` }}
          </a-descriptions-item>
          <a-descriptions-item label="是否主服务器">
            <a-tag :color="currentRelation.relation.isPrimary === 1 ? 'green' : 'gray'">
              {{ currentRelation.relation.isPrimary === 1 ? '是' : '否' }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="连接状态">
            <a-tag :color="getConnectionStatusColor(currentRelation.relation.connectionStatus)">
              {{ getConnectionStatusText(currentRelation.relation.connectionStatus) }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="服务器状态">
            <a-tag :color="currentRelation.server.status === 1 ? 'green' : 'red'">
              {{ currentRelation.server.status === 1 ? '在线' : '离线' }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="创建时间">{{ formatTime(currentRelation.relation.createTime) }}</a-descriptions-item>
          <a-descriptions-item label="更新时间">{{ formatTime(currentRelation.relation.updateTime) }}</a-descriptions-item>
          <a-descriptions-item label="创建人">{{ currentRelation.relation.createBy }}</a-descriptions-item>
          <a-descriptions-item label="更新人">{{ currentRelation.relation.updateBy }}</a-descriptions-item>
        </a-descriptions>
      </div>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { Message, Modal } from '@arco-design/web-vue';
import { useRoute, useRouter } from 'vue-router';
import useLoading from '@/hooks/loading';
import axios from 'axios';
import type { FormInstance } from '@arco-design/web-vue';

// 服务器关联数据接口
interface ServerRelation {
  relation: {
    id: number;
    pileId: number;
    serverId: number;
    isPrimary: number;
    connectionStatus: number;
    createBy: string;
    createTime: string;
    updateBy: string;
    updateTime: string;
    forwardPileCode: string;
  };
  pile: {
    id: number;
    pileName: string;
    pileCode: string;
    stationId: number;
    pileType: number;
    status: number;
    sortOrder: number;
  };
  server: {
    id: number;
    serverName: string;
    serverIp: string;
    serverPort: number;
    status: number;
    platformId: number;
  };
}

// 转发服务器接口
interface ForwardServer {
  id: number;
  serverName: string;
  serverIp: string;
  serverPort: number;
  serverType: number;
  status: number;
  remark: string;
}

// 获取路由参数
const route = useRoute();
const router = useRouter();
const deviceId = ref<number | null>(null);
const deviceName = ref<string>('');

// 加载状态
const { loading, setLoading } = useLoading();

// 对话框状态
const visible = ref(false);
const detailVisible = ref(false);
const isEdit = ref(false);
const formRef = ref<FormInstance | null>(null);
const currentRelation = ref<ServerRelation | null>(null);

// 服务器关联列表
const relationList = ref<ServerRelation[]>([]);

// 转发服务器列表
const serverList = ref<ForwardServer[]>([]);

// 分页
const pagination = reactive({
  total: 0,
  current: 1,
  pageSize: 10,
  showTotal: true,
  showJumper: true,
  showPageSize: true,
});

// 表单数据
interface FormState {
  id?: number;
  serverId: number | undefined;
  isPrimary: number;
  connectionStatus: number;
  pileId: number;
  forwardPileCode: string;
}

const formInitialState: FormState = {
  serverId: undefined,
  isPrimary: 0,
  connectionStatus: 0,
  pileId: 0,
  forwardPileCode: '',
};

const form = reactive<FormState>({ ...formInitialState });

// 表单验证规则
const rules = {
  serverId: [{ required: true, message: '请选择转发服务器' }],
};

// 获取连接状态文本
function getConnectionStatusText(status: number) {
  switch (status) {
    case 0:
      return '未连接';
    case 1:
      return '已连接';
    case 2:
      return '连接异常';
    default:
      return '未知状态';
  }
}

// 获取连接状态颜色
function getConnectionStatusColor(status: number) {
  switch (status) {
    case 0:
      return 'gray';
    case 1:
      return 'green';
    case 2:
      return 'red';
    default:
      return 'gray';
  }
}

// 格式化时间
function formatTime(time?: string) {
  if (!time) return '未知';
  return time.replace('T', ' ').substring(0, 19);
}

// 获取服务器关联列表数据
async function fetchData() {
  if (!deviceId.value) {
    Message.error('充电桩ID不能为空');
    return;
  }
  
  setLoading(true);
  try {
    const params = {
      current: pagination.current,
      pageSize: pagination.pageSize,
      pileId: deviceId.value,
    };
    
    const response = await axios.get('/api/pile/server/relation/page', { params });
    relationList.value = response.data.records;
    pagination.total = response.data.total;
  } catch (error) {
    console.error('获取服务器关联列表失败:', error);
    Message.error('获取服务器关联列表失败');
  } finally {
    setLoading(false);
  }
}

// 分页变化
function onPageChange(current: number) {
  pagination.current = current;
  fetchData();
}

// 每页条数变化
function onPageSizeChange(pageSize: number) {
  pagination.pageSize = pageSize;
  pagination.current = 1;
  fetchData();
}

// 获取转发服务器列表
async function fetchServerList() {
  try {
    const response = await axios.get('/api/forward/server/list');
    serverList.value = response.data;
  } catch (error) {
    console.error('获取转发服务器列表失败:', error);
    Message.error('获取转发服务器列表失败');
  }
}

// 在 script 部分添加
const pileCode = ref<string>('');

// 获取充电桩信息
async function fetchPileInfo() {
  if (!deviceId.value) return;
  
  try {
    const response = await axios.get(`/api/charging/pile/${deviceId.value}`);
    if (response.data) {
      pileCode.value = response.data.pileCode;
    }
  } catch (error) {
    console.error('获取充电桩信息失败:', error);
    Message.error('获取充电桩信息失败');
  }
}

// 修改 openAddDialog 函数
function openAddDialog() {
  isEdit.value = false;
  fetchPileInfo(); // 获取充电桩信息
  
  Object.assign(form, {
    ...formInitialState,
    pileId: deviceId.value || 0,
  });
  fetchServerList(); // 获取服务器列表
  visible.value = true;
}

// 修改 openEditDialog 函数
function openEditDialog(relation: ServerRelation) {
  isEdit.value = true;
  pileCode.value = relation.pile.pileCode;
  Object.assign(form, {
    id: relation.relation.id,
    serverId: relation.relation.serverId,
    isPrimary: relation.relation.isPrimary,
    connectionStatus: relation.relation.connectionStatus,
    pileId: relation.relation.pileId,
    forwardPileCode: relation.relation.forwardPileCode,
  });
  fetchServerList(); // 获取服务器列表
  visible.value = true;
}

// 查看服务器关联详情
function viewRelationDetail(relation: ServerRelation) {
  currentRelation.value = relation;
  detailVisible.value = true;
}

// 处理表单提交
const handleSubmit = async () => {
  if (!formRef.value) {
    console.error('表单引用不存在');
    return;
  }
  
  try {
    // 表单验证
    await formRef.value.validate();
    
    setLoading(true);
    
    if (isEdit.value) {
      // 编辑服务器关联
      const params = {
        id: form.id,
        serverId: form.serverId,
        isPrimary: form.isPrimary,
        connectionStatus: form.connectionStatus,
        pileId: form.pileId,
        forwardPileCode: form.forwardPileCode,
      };
      
      try {
        // 使用自定义请求处理
        const headers = new Headers();
        headers.append('Content-Type', 'application/json');
        
        const response = await fetch(`/api/pile/server/relation/${form.id}`, {
          method: 'PUT',
          headers: headers,
          body: JSON.stringify(params),
        });
        
        const result = await response.json();
        console.log('编辑请求返回:', result);
        
        // 根据返回的 code 判断请求是否成功
        if (result.code === 200) {
          Message.success('编辑服务器关联成功');
          visible.value = false;
          fetchData(); // 刷新列表
        } else {
          // 显示服务器返回的错误信息
          Message.error(result.message || '编辑服务器关联失败');
        }
      } catch (error) {
        console.error('编辑服务器关联异常:', error);
        Message.error('编辑服务器关联失败，请检查网络连接');
      }
    } else {
      // 新增服务器关联
      const params = {
        serverId: form.serverId,
        isPrimary: form.isPrimary,
        connectionStatus: form.connectionStatus,
        pileId: deviceId.value,
        forwardPileCode: form.forwardPileCode,
      };
      
      try {
        // 使用自定义请求处理
        const headers = new Headers();
        headers.append('Content-Type', 'application/json');
        
        const response = await fetch('/api/pile/server/relation', {
          method: 'POST',
          headers: headers,
          body: JSON.stringify(params),
        });
        
        const result = await response.json();
        console.log('新增请求返回:', result);
        
        // 根据返回的 code 判断请求是否成功
        if (result.code === 200) {
          Message.success('新增服务器关联成功');
          visible.value = false;
          fetchData(); // 刷新列表
        } else {
          // 显示服务器返回的错误信息
          Message.error(result.message || '新增服务器关联失败');
        }
      } catch (error) {
        console.error('新增服务器关联异常:', error);
        Message.error('新增服务器关联失败，请检查网络连接');
      }
    }
  } catch (error) {
    console.error('表单验证失败:', error);
  } finally {
    setLoading(false);
  }
};

// 删除服务器关联
function handleDelete(relation: ServerRelation) {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除充电桩 "${relation.pile.pileName}" 的服务器关联吗？此操作不可恢复。`,
    onOk: async () => {
      setLoading(true);
      try {
        await axios.delete(`/api/pile/server/relation/${relation.relation.id}`);
        Message.success('删除服务器关联成功');
        fetchData(); // 刷新列表
      } catch (error) {
        console.error('删除服务器关联失败:', error);
        Message.error('删除服务器关联失败');
      } finally {
        setLoading(false);
      }
    },
  });
}

// 返回充电桩列表
function goBack() {
  console.log('返回参数:', {
    stationId: route.query.stationId,
    stationName: route.query.stationName,
    pileName: route.query.pileName,
    pileType: route.query.pileType,
    status: route.query.status,
    current: route.query.current,
    pageSize: route.query.pageSize
  });
  
  router.push({
    path: '/station/device',
    query: {
      stationId: route.query.stationId,
      stationName: route.query.stationName,
      pileName: route.query.pileName,
      pileType: route.query.pileType,
      status: route.query.status,
      current: route.query.current,
      pageSize: route.query.pageSize
    }
  });
}

// 刷新数据
function refreshData() {
  pagination.current = 1;
  fetchData();
  Message.success('数据已刷新');
}

onMounted(() => {
  // 获取路由参数
  if (route.query.deviceId) {
    deviceId.value = Number(route.query.deviceId);
  }
  if (route.query.deviceName) {
    deviceName.value = route.query.deviceName as string;
  }
  
  // 获取充电桩信息
  fetchPileInfo();
  
  // 获取服务器关联列表
  fetchData();
  
  // 获取转发服务器列表
  fetchServerList();
});
</script>

<style scoped lang="less">
.container {
  padding: 0 20px 20px 20px;
}

.operation-bar {
  margin-bottom: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  .operation-left {
    display: flex;
    gap: 8px;
  }
  
  .operation-right {
    display: flex;
    gap: 8px;
  }
}

.relation-modal {
  :deep(.arco-modal-header) {
    border-bottom: 1px solid var(--color-border-2);
    padding: 16px 20px;
    
    .arco-modal-title {
      font-size: 18px;
      font-weight: 500;
    }
  }
  
  :deep(.arco-modal-body) {
    padding: 20px;
  }
}

.relation-form {
  .form-footer {
    display: flex;
    justify-content: center;
    margin-top: 24px;
    
    .arco-space {
      .arco-btn {
        min-width: 80px;
      }
    }
  }
}

.relation-detail {
  :deep(.arco-descriptions) {
    background-color: var(--color-bg-2);
  }
}
</style> 